clc
clear all
deltah=0.2;ndeltah=81;


for deltatn=1:1:ndeltah
  kom=deltatn;
  ir=0;
  jr=0;
  count=0;
  for i=-1:deltah*2:1
      for j=-1:deltah:1
          if (i^2+j^2<=1.00001)
              count=count+1;
              if (count==kom)
                  ir=i;
                  jr=j;
              end
          end
      end
      i=i+deltah;
      for j=1:-deltah:-1
          if (i^2+j^2<=1.00001)
              count=count+1;
              if (count==kom)
                  ir=i;
                  jr=j;
              end
          end
      end
   end
  xxx(kom,1:3)=[deltatn-1 jr ir];
end


% A program to find the controller parameter of a Synchronous- 
%-reference frame current controller.
%Parameters are:
%fs=switching frequency, fco=cross over frequrncy, Vdc= DC link voltage
%Rs= filter resistance, Ls=filter (with quality factor of 30, in 60 Hz);
%GTI=transduver gain, f0=system frquency, Q=quality factor
%phm= phase margine
C=900e-6;
phm=60;
f0=60;
w0=2*pi*f0
Q=30;
fsw=8e3;
Ts=1/fsw
Vdc=600;
Ls=.75e-3;
Rs=(2*pi*f0)*Ls/Q;
fco=fsw/25;
wco=2*pi*fco;
Gti=1;
P=150e3;
RL=Vdc^2/P;
Kp=(Rs)*(1+(wco*Ls/Rs)^2)^.5
Ki=(wco*Kp)/(tand(-90+phm+2*atand(wco*Ts/4)+atand(wco*Ls/Rs)))


Kp0=wco*Ls/(2*Vdc/Gti);
Ki0=[(wco*Kp)/tand(phm-90+atand(wco*Ls/Rs))];
%Kp=(Rs/(2*Vdc*Gti))*(1+(wco*Ls/Rs)^2)^.5
%Ki=(wco*Kp)/(tand(-90+phm+2*atand(wco*Ts/4)+atand(wco*Ls/Rs)))
%Ki=1/2*Ki;

%Chwu

Gps = tf([0 1],[Ls Rs]);
Kp1=Rs*sqrt(1+(wco*Ls/Rs)^2)
Ki1=wco*Kp1/tand(-90+phm+2*atan(wco*Ts/4)*180/pi+atan(wco*Ls/Rs)*180/pi)
Gc=tf([Kp Ki],[1 0]);
Gpwm = tf([-Ts/4 1],[Ts/4 1])
G = Gc * Gpwm * Gps * Gti;
figure(1)
bode(G); grid [on];


figure(2)
Kn=Gti*2*Vdc;
w=logspace(2,5);
num=Kn*[Kp, 2*Ki, Kp*w0^2];
denum=[Ls,Rs,Ls*w0^2,Rs*w0^2];
bode(num,denum,w);